import os, zipfile
import shutil
from jinja2 import Environment, FileSystemLoader, PackageLoader
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties


class ExportReport():
    def __init__(self, order_num):
        self.report_dir = "Report/samereport_" + order_num
        self.SENTENCE_ENVIRONMENT = Environment(
            autoescape=True,
            loader=PackageLoader('ExportReport', 'report_templates'),
            trim_blocks=False)
        if not self.is_exists_report():
            os.mkdir("Report/samereport_" + order_num)

    def sentence_render_template(self, template_filename, contexts):
        return self.SENTENCE_ENVIRONMENT.get_template(template_filename).render(contexts=contexts)

    @classmethod
    def get_MD5(cls, file_path):
        files_md5 = os.popen('md5 %s' % file_path).read().strip()
        file_md5 = files_md5.replace('MD5 (%s) = ' % file_path, '')
        return file_md5

    def create_report_directory(self, path='', out=''):
        if path == '':
            path = 'ExportReport/report_templates/samereport'
        if out == '':
            out = self.report_dir
        for files in os.listdir(path):
            name = os.path.join(path, files)
            back_name = os.path.join(out, files)
            if os.path.isfile(name):
                if os.path.isfile(back_name):
                    if self.get_MD5(name) != self.get_MD5(back_name):
                        shutil.copy(name, back_name)
                else:
                    shutil.copy(name, back_name)
            else:
                if not os.path.isdir(back_name):
                    os.makedirs(back_name)
                self.create_report_directory(name, back_name)

    def create_index_html(self, index, contexts, xiugaiyijian):
        fname = self.report_dir + "/htmls/sentence_detail/detail_" + index + ".html"
        sentences = []
        for index, context in enumerate(contexts):
            info = {
                'original_content': context.original_content,
                'similar_content': context.similar_content,
                'rate': int(context.rate * 100),
                'source': context.source,
                'title': context.title,
                'author': context.author
            }
            sentences.append(info)
        with open(fname, 'w') as f:
            html = self.SENTENCE_ENVIRONMENT.get_template('detail.html').render(contexts=sentences,
                                                                                xiugaiyijian=xiugaiyijian)
            f.write(html)

    def create_xueshu_index_html(self, index, contexts, xiugaiyijian=''):
        fname = self.report_dir + "/htmls/sentence_detail/detail_" + index + ".html"
        with open(fname, 'w') as f:
            html = self.SENTENCE_ENVIRONMENT.get_template('xueshu_detail.html').render(contexts=contexts,
                                                                                       xiugaiyijian=xiugaiyijian)
            f.write(html)

    def create_paper_html(self, contexts):
        fname = self.report_dir + "/htmls/detail_report/paper.html"
        with open(fname, 'w') as f:
            html = self.sentence_render_template('paper.html', contexts=contexts)
            f.write(html)

    def create_pdf_html(self, contexts, local, internet, view_info):
        fname = self.report_dir + "/htmls/pdf.html"
        with open(fname, 'w') as f:
            html = self.SENTENCE_ENVIRONMENT.get_template('pdf.html').render(contexts=contexts, local=local,
                                                                             internet=internet, view_info=view_info)
            f.write(html)
        if os.path.exists(self.report_dir + "/htmls/pdf.html"):
            # (stop_status, output) = subprocess.getstatusoutput('xvfb-run wkhtmltopdf '+self.report_dir + "/htmls/pdf.html "+self.report_dir + "/简明打印版.pdf")
            os.system('wkhtmltopdf ' + self.report_dir + "/htmls/pdf.html " + self.report_dir + "/简明打印版.pdf")
            # print(output)

    def create_report_html(self, contexts):
        fname = self.report_dir + "/检测报告详细版.html"
        with open(fname, 'w') as f:
            html = self.sentence_render_template('检测报告详细版.html', contexts=contexts)
            f.write(html)

    def create_orginal_html(self, contexts):
        fname = self.report_dir + "/htmls/view_original_.html"
        with open(fname, 'w') as f:
            html = self.sentence_render_template('view_original_.html', contexts=contexts)
            f.write(html)

    def create_ScatterDiagram(self, orange_data, red_data, max_x):
        fname = self.report_dir + '/images/da_img.png'
        font = FontProperties(fname="ExportReport/simsun.ttc", size=14)
        plt.figure(figsize=(12.3, 3), tight_layout=True)
        plt.scatter(red_data[0], red_data[1], s=40, c='r', marker='.')
        plt.scatter(orange_data[0], orange_data[1], s=40, c='y', marker='.')
        plt.axis([-5, max_x + 5, 40, 105])
        plt.grid()
        plt.ylabel('Y-相似度', fontsize=10, fontproperties=font)
        plt.xlabel('X-句子', fontsize=10, fontproperties=font)
        plt.title('不合格句子点状分布图', fontsize=10, fontproperties=font)
        plt.savefig(fname)

    def create_barcode(self, data):
        fname = self.report_dir + '/images/xiao_img.png'
        font = FontProperties(fname="ExportReport/simsun.ttc", size=14)
        fig = plt.figure(figsize=(11.3, 1))
        ax = fig.add_axes([0, 0, 1, 1])  # span the whole figure
        ax.set_axis_on()
        ax.imshow(data, cmap='RdYlGn_r', aspect='auto',
                  interpolation='none')
        plt.xlabel('句子相似度分布图', fontsize=10, fontproperties=font)
        plt.savefig(fname)

    def create_assess_html(self, local, internet, view_info):
        fname = self.report_dir + '/htmls/counta.html'
        with open(fname, 'w') as f:
            html = self.SENTENCE_ENVIRONMENT.get_template('counta.html').render(local=local, internet=internet,
                                                                                view_info=view_info)
            f.write(html)

    def zip_report(self):
        zipf = zipfile.ZipFile(self.report_dir + '.zip', 'w')
        pre_len = len(os.path.dirname(self.report_dir))
        for parent, dirnames, filenames in os.walk(self.report_dir):
            for filename in filenames:
                pathfile = os.path.join(parent, filename)
                arcname = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
                zipf.write(pathfile, arcname)
        zipf.close()
        shutil.rmtree(self.report_dir)

    def is_exists_report(self):
        if os.path.exists(self.report_dir + '.zip'):
            return True
        else:
            return False


if __name__ == '__main__':
    s = ExportReport('123')
    s.create_report_directory()
